// components/progress-bar/progress-bar.js

let movableAreaWidth = 0
let movableViewWidth = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
let currentSec = -1
let duration = 0 //以秒为单位的总时长
let isMoving = false //当前进度条是否在拖拽，解决进度条拖动的时候跟updatetime冲突的问题
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isSame:Boolean
  },

  /**
   * 组件的初始数据
   */
 
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00'
    },
    movableDis: 0,
    progress: 0
  },

  lifetimes: {
    ready() {
      if(this.properties.isSame && this.data.showTime.totalTime == '00:00'){
        this._setTime()
      }
      this._getMovableDis()
      this._bindBGMEvent()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event) {
      // console.log(event.detail)
      if (event.detail.source == 'touch') {
        this.data.progress = event.detail.x / (movableAreaWidth - movableViewWidth) * 100
        this.data.movableDis = event.detail.x
        isMoving = true
       console.log("change",isMoving)

      }
    },

    OnTouchEnd() {
      const currentTimeFmt = this._dateFormat(Math.floor(backgroundAudioManager.currentTime))

      this.setData({
        progress: this.data.progress,
        movableDis: this.data.movableDis,
        ['showTime.currentTime']: currentTimeFmt.min + ":" + currentTimeFmt.sec
      })
      backgroundAudioManager.seek(duration * this.data.progress / 100)
      isMoving = false
      console.log("end",isMoving)
    },

    _getMovableDis() {
      const query = this.createSelectorQuery()
      query.select('.movable-area').boundingClientRect()
      query.select('.movable-view').boundingClientRect()
      query.exec((rect) => {
        movableAreaWidth = rect[0].width
        movableViewWidth = rect[1].width

      })

    },
    _bindBGMEvent() {
      backgroundAudioManager.onPlay(() => {
        isMoving = false
        console.log("play",isMoving)
        this.triggerEvent("musicPlay")
      })
      backgroundAudioManager.onStop(() => {

      })
      backgroundAudioManager.onPause(() => {
        this.triggerEvent("musicPause")

      })
      backgroundAudioManager.onWaiting(() => {

      }),
      backgroundAudioManager.onNext(()=>{
        this.triggerEvent("musicNext")
        console.log("next")
      }),
      backgroundAudioManager.onPrev(()=>{
        this.triggerEvent("musicPrev")

      })
      backgroundAudioManager.onCanplay(() => {
        if (backgroundAudioManager.duration != null) {
          this._setTime()
        } else {
          setTimeout(() => {
            this._setTime()
          }, 1000)
        }
      })
      backgroundAudioManager.onTimeUpdate(() => {
        if (!isMoving) {
          const currentTime = backgroundAudioManager.currentTime // 当前音频的播放位置（单位：s）,只有在合法的src时返回
          const duration = backgroundAudioManager.duration
          const sec = currentTime.toString().split(".")[0]
          // 一秒内会触发4次onTimeUpdate函数。所以只改变秒速不一样的事件点
          if (sec != currentSec) {
            const currentTimeFmt = this._dateFormat(currentTime)
            this.setData({
              movableDis: (movableAreaWidth - movableViewWidth) * currentTime / duration,
              progress: currentTime / duration * 100,
              ["showTime.currentTime"]: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
            })
            currentSec = sec
            //联动歌词
            this.triggerEvent("timeUpdate",{
              currentTime
            })
          }
       }


      })
      backgroundAudioManager.onEnded(() => {
        this.triggerEvent('musicEnd')
      })
      backgroundAudioManager.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode)
        wx.showToast({
          title: '错误' + res.errCode,
        })

      })
    },
    _setTime() {
      duration = backgroundAudioManager.duration
      const totalTime = this._dateFormat(duration).min + ":" + this._dateFormat(duration).sec
      this.setData({
        ['showTime.totalTime']: totalTime
      })

    },
    _dateFormat(sec) {
      const min = Math.floor(sec / 60)
      sec = Math.floor(sec % 60)
      return {
        "min": this._parse0(min),
        "sec": this._parse0(sec)
      }
    },
    _parse0(sec) {
      return sec < 10 ? "0" + sec : sec
    }
  }
})